 package com.appjishu.web.util.pubsub;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.listener.PatternTopic;
import org.springframework.data.redis.listener.RedisMessageListenerContainer;
import org.springframework.data.redis.listener.adapter.MessageListenerAdapter;

import cn.hutool.system.SystemUtil;
/**
 * @author edmond
 * @date 2020/05/20
 */
@Configuration
public class PubSubConfig {
    // 避免分布式部署重复消费
    public static final String pubsubPrefix = "pubsub_" + SystemUtil.getHostInfo().getAddress() + "_" + SystemUtil.getRuntimeMXBean().getName().split("@", 2)[0];
    
    @Bean
    RedisMessageListenerContainer container(
        RedisConnectionFactory connectionFactory, MessageListenerAdapter listenerAdapter) {
        RedisMessageListenerContainer container = new RedisMessageListenerContainer();
        container.setConnectionFactory(connectionFactory);
        for (EventType type : EventType.values()) {
            container.addMessageListener(listenerAdapter, new PatternTopic(pubsubPrefix + type.name()));
        }
        return container;
    }
}

 